package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author zkx
 */
public class SimpleLock implements ILock{

    private String name;
    private final StringRedisTemplate redisTemplate;

    public SimpleLock(String name, StringRedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unLock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(Long time) {
        //得到锁
        String id = ID_PREFIX + Thread.currentThread().getId();
        Boolean aBoolean =
                redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, id, time, TimeUnit.SECONDS);
        //如果直接对aBoolean返回，可能会出现空指针
        return Boolean.TRUE.equals(aBoolean);
    }

//    @Override
//    public void unLock() {
//        String s = redisTemplate.opsForValue().get(KEY_PREFIX + name);
//        //进程号相等
//        if(s==null){
//            return;
//        }
//        if(s.equals(ID_PREFIX + Thread.currentThread().getId())){
//            redisTemplate.delete(KEY_PREFIX + name);
//        }
//    }
    @Override
    public void unLock() {
        redisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }
}
